﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;

namespace homework10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private delegate void MyDelegate();
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Thread thread1 = new Thread(new ThreadStart(baidu_search));
                Thread thread2 = new Thread(new ThreadStart(bing_search));
                thread1.Start();
                thread2.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
         }
      

        private void parallelprogram_Click(object sender, EventArgs e)
        {
            try
            {
                Task task_baidu = new Task(() => { baidu_search(); });
                Task task_bing = new Task(() => { bing_search(); });
                task_baidu.Start();
                task_bing.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

       
        private string searchMessage(string engine)
        {
            try
            {
                String url = engine + searchTextbox.Text;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader sr = new StreamReader(stream);
                string str = sr.ReadToEnd();
                string webTxt = "";
                string pattern = @"[\u4e00-\u9fa5]+";
                foreach (Match match in Regex.Matches(str, pattern))
                {
                    webTxt += match.Value;
                }
                return webTxt;
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }

        }
        
        private void baidu_search()
        {
           string s= searchMessage("https://www.baidu.com/baidu?wd=");
            this.BeginInvoke(new MyDelegate(() => { baidutextBox.Text = s; }));
        }
       private void bing_search()
        {
          string s=  searchMessage("https://cn.bing.com/search?q=");
            this.BeginInvoke(new MyDelegate(() => { bingtextBox.Text = s.Substring(0, 200); }));
        }
    }
}
